package com.soulapp.hook.hooker

import android.annotation.SuppressLint
import android.widget.Toast
import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData

// 禁止发送输入状态
object LimitMsgStateHook : BaseHooker() {
    private const val TAG = "LimitMsgInputHook"
    private var hook: Result? = null

    override fun getKey() = ConfigData.limitMsg

    override fun onHook() {
        startHook()
    }

    @SuppressLint("SimpleDateFormat")
    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        val className = "cn.soulapp.imlib.msg.ImMessage"
        hook = className.toClass().resolve()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("setMsgType")
                parameters(Int::class.java)
                returnType == Void::class.javaPrimitiveType
            }.first()
            .hook {
                before {
                    val msgType = args[0]
                    val showToast = ConfigData.getBoolean(ConfigData.showToast)
                    when (msgType) {
                        // 禁止信息撤回
                        9 -> {
                            args[0] = 23
                            if (showToast) {
                                Toast.makeText(appContext, "禁止信息撤回", Toast.LENGTH_SHORT).show()
                            }
                        }
                        // 禁止发送输入状态
                        22 -> {
                            args[0] = 23
                            if (showToast) {
                                Toast.makeText(appContext, "禁止发送输入状态", Toast.LENGTH_SHORT).show()
                            }
                        }
                        // 禁止发送回执信息
                        25 -> {
                            args[0] = 23
                            if (showToast) {
                                Toast.makeText(appContext, "禁止发送回执信息", Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                }
            }
    }

    override fun stopHook() {
        YLog.debug("stopHook $TAG $hookEnabled")
        if (hookEnabled) return

        hook?.let {
            it.remove {
                YLog.debug("stopHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook $TAG 失败")
    }

}
